﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ListViewShowIndex
{
    public class MainViewModel
    {
        public ObservableCollection<StudentModel> Students { get; set; }

        public CommandBase AddCommand { get; set; }
        public CommandBase RemoveCommand { get; set; }

        public MainViewModel()
        {
            InitStudents();
            InitCommand();
        }

        private void Students_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            int index = 0;

            if (e.NewStartingIndex != -1)
            {
                index = e.NewStartingIndex;
            }
            else
            if (e.OldStartingIndex != -1)
            {
                index = e.OldStartingIndex;
            }

            var collection = sender as ObservableCollection<StudentModel>;

            for (int i = index; i < collection.Count; i++)
            {
                collection[i].Index = i + 1;
            }
        }

        private void InitCommand()
        {
            AddCommand = new CommandBase();
            AddCommand.DoExecute += AddCommand_DoExecute;


            RemoveCommand = new CommandBase();
            RemoveCommand.DoExecute += RemoveCommand_DoExecute; ;
        }

        private void RemoveCommand_DoExecute(object obj)
        {
            if (Students.Count > 0)
                Students.RemoveAt(1);
        }

        int _tmpIndex = 15;
        private void AddCommand_DoExecute(object obj)
        {
            Students.Add(new StudentModel() { Name=$"Name{_tmpIndex++}"});
        }

        private void InitStudents()
        {
            Students = new ObservableCollection<StudentModel>()
            {
                new StudentModel(){ Name="Name1"},
                new StudentModel(){ Name="Name2"},
                new StudentModel(){ Name="Name3"},
                new StudentModel(){ Name="Name4"},
                new StudentModel(){ Name="Name5"},
                new StudentModel(){ Name="Name6"},
                new StudentModel(){ Name="Name7"},
                new StudentModel(){ Name="Name8"},
                new StudentModel(){ Name="Name9"},
                new StudentModel(){ Name="Name10"},
                new StudentModel(){ Name="Name11"},
                new StudentModel(){ Name="Name12"},
                new StudentModel(){ Name="Name13"},
                new StudentModel(){ Name="Name14"},
            };

            Students.CollectionChanged += Students_CollectionChanged;

            int index = 0;
            foreach (var item in Students)
            {
                item.Index = ++index;
            }
        }
    }
}
